/**
 * 单个节点
 */
class Node {
  /**
   * 单个节点
   * @param {any} el 任意数据
   * @param {any} next 下一个数据
   */
  constructor(el, next) {
    this.el = el
    this.next = next
  }
}

class Linked {
  constructor() {
    this.head = null
    this.size = 0
  }

  get(index) {
    if (index < 0 || index >= this.size) {
      throw new Error('越界了')
    }
    let currentNode = this.head
    for (let i = 0; i < index; i++) {
      currentNode = currentNode.next
    }
    return currentNode
  }

  add(index, el) {
    if (arguments.length === 0) return this
    if (arguments.length === 1) {
      el = index
      index = this.size
    }
    if (index === 0) {
      const head = this.head
      this.head = new Node(el, head)
    } else {
      const preNode = this.get(index - 1)
      preNode.next = new Node(el, preNode.next)
    }
    this.size++
    return this
  }

  del(index) {
    if (index < 0 || index >= this.size) {
      throw new Error('越界了')
    }
    if (index === 0) {
      const head = this.head
      this.head = head.next
      this.size--
      return head
    }
    const currentNode = this.get(index)
    const preNode = this.get(index - 1)
    preNode.next = currentNode.next
    this.size--
    return currentNode
  }
}
const l = new Linked()
l.add('node1').add(1, 'node2')
l.del(1)
l.del(0)
console.log(l)